package com.rcp.manager;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


@WebServlet("/MenuManagerServlet")
public class MenuManagerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	Connection connection = Nexus.connection;
	Menu menu;


    public MenuManagerServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		//Check if connection is active
		if(this.connection == null){
			establishConnection();
		} else
			try {
				if(this.connection.isClosed()){
					establishConnection();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		
		//Get menu
		int menuID = Integer.parseInt(request.getParameter("selected"));
		//System.out.println(menuID);
		
		try {
			String preparedQuery = 
					"SELECT menu FROM Menus WHERE menuID = ?;";
			
			PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ps.setInt(1, menuID);
			
			ResultSet results = ps.executeQuery();
			results.first();
			
			//Reading Object from BLOB
			//http://hans.liss.pp.se/node/700
			InputStream is = results.getBlob("menu").getBinaryStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			Object o = null;
			
			try {	
				o = ois.readObject();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} 
			
			this.menu = (Menu) o;

		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//Print out menu
		out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

		out.println("<html>");

		out.println("<head>");

		out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");

		out.println("<title>Staff</title>");

		out.println("<link href=\"resources/CSS/Selected.css\" rel=\"stylesheet\" type=\"text/css\"/>");

		out.println("</head>");

		out.println("<script type='text/javascript'>");

		out.println("function toggle_visibility(id) {");

		out.println("var e = document.getElementById(id);");

		out.println("if(e.style.display == 'block')");

		out.println("e.style.display = 'none';");

		out.println("else");

		out.println("e.style.display = 'block';");

		out.println("}");

		out.println("</script>");

		out.println("<body>");
		
		//
		
		out.println("<form name='erase' action='MenuManagerServlet' method='post'>");
		
		out.println("<input type='hidden' name='menuID' value='" + menu.getMenuID() + "'></input>");
		
		out.println("<table class='del'>");
		
		out.println("<tr>");
		
		out.println("<td>");
		
		out.println("<h1>" + menu.getName() + "</h1>");
		
		out.println("</td>");
		
		out.println("<td>");
		
		out.println("<button class='glass' name='delete' type='submit' value='" +  menu.getMenuID() +"'>Delete</button>");
		
		out.println("</td>");
		
		out.println("</table>");
		
		out.println("</form>");
		
		out.println("<hr />");
		
		out.println("<br />");
		
		//Print out everything
		LinkedHashMap<String, Integer> entrees = menu.getEntrees();
		LinkedHashMap<String, Integer> sides = menu.getSides();
		LinkedHashMap<String, Integer> drinks = menu.getDrinks();
		
		Set<String> en = entrees.keySet();
		Set<String> si = sides.keySet();
		Set<String> dr = drinks.keySet();
	
		
		Object[] e = en.toArray();
		Object[] s = si.toArray();
		Object[] d = dr.toArray();

		
		out.println("<div class='center'>");
		
		out.println("<h1>Main Course:</h1>");
		
		out.println("<table>");

		for(int i = 0; i < e.length; i++){
			out.println("<tr>");

			out.println("<td>" + e[i] + "</td>");

			out.println("<td> x </td>");

			out.println("<td>" + entrees.get(e[i]) + "</td>");

			out.println("</tr>");
			
		}
		
		out.println("</table>");

		out.println("<br />");
		
		out.println("<h1>Sides:</h1>");
		
		out.println("<table>");
				
		for(int i = 0; i < s.length; i++){
			out.println("<tr>");

			out.println("<td>" + s[i] + "</td>");

			out.println("<td> x </td>");

			out.println("<td>" + sides.get(s[i]) + "</td>");

			out.println("</tr>");
		}
		
		out.println("</table>");
		
		out.println("<br />");
		
		out.println("<h1>Drinks:</h1>");
		
		out.println("<table>");
		
		for(int i = 0; i < d.length; i++){
			out.println("<tr>");

			out.println("<td>" + d[i] + "</td>");

			out.println("<td> x </td>");

			out.println("<td>" + drinks.get(d[i]) + "</td>");

			out.println("</tr>");
		}
		
		out.println("</table>");

		out.println("<br />");
		
		out.println("<br />");
		
		out.println("<br />");
		
		out.println("</div>");
		
		out.println("</body>");

		out.println("</html>");

		out.close();
		
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int menuID = Integer.parseInt(request.getParameter("menuID"));

		
		if(request.getParameter("delete") != null){
			try {
				String preparedQuery = 
						"DELETE FROM Menus WHERE menuID = ?;";
				
				PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
				ps.setInt(1, menuID);
				
				ps.executeUpdate();
				
				response.sendRedirect("MenusTable");
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
	}
	
	public void establishConnection(){
		
		String dbURL = "jdbc:mysql://cs3.calstatela.edu:3306/cs437group01";
		String dbName = "";
		String username = "cs437group01";
		String password = "VHj#dj!v";
		String driver = "com.mysql.jdbc.Driver";
		 
		/*
		String dbURL = "jdbc:mysql://localhost:3306/";
		String dbName = "rcp";
		String username = "root";
		String password = "sesame";
		String driver = "com.mysql.jdbc.Driver";
		*/
		
		try {
			Class.forName(driver).newInstance();
			Nexus.connection = (Connection) DriverManager.getConnection(dbURL + dbName, username, password);
			this.connection = Nexus.connection;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void destroy(){
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		super.destroy();
	}


}
